package com.vess.ratingweb;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;

import com.vess.ratingweb.model.JDBCAdapter;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.view.ViewPager.LayoutParams;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

public class Directory extends Activity {

	private String mStrUsername;
	private String mStrTimeStamp;
	private JDBCAdapter mJDBC;
	private ArrayList<ContentValues> mArrLstSitesUsers;
	private LinearLayout mLiLayStore;
	private int[] mIntImage;
	private String[] mStrBuisURL;
	private String mStrLogo;
	private String mStrIcon, mStrCoupon;
	private int mIntUserId;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.directory);

		mLiLayStore = (LinearLayout) findViewById(R.id.linInfo);

		mStrUsername = getIntent().getStringExtra("username");
		mStrTimeStamp = getIntent().getStringExtra("timestamp");
		mStrLogo = getIntent().getStringExtra("logo");
		mStrCoupon = getIntent().getStringExtra("coupon");
		mIntUserId = getIntent().getIntExtra("id", 0);

		mJDBC = new JDBCAdapter(Directory.this);
		mArrLstSitesUsers = new ArrayList<ContentValues>();

		if (mStrUsername != null) {
			loadSitesUsers();
		}

		new DownloadImageTask((ImageView) findViewById(R.id.imgDirLogo))
				.execute("http://reputation.bonothemes.com/user/php/uploads/"
						+ mStrLogo);

		/*
		 * imgYahoo.setOnClickListener(new OnClickListener() {
		 * 
		 * @Override public void onClick(View v) { startActivity(new
		 * Intent(Directory.this, RatingPage.class) .putExtra("url",
		 * "http://www.yahoo.com"));
		 * 
		 * Intent inDir = new Intent(Directory.this, RatingPage.class);
		 * inDir.putExtra("url", "https://www.dealerrater.com/login.aspx");
		 * inDir.putExtra("id",mIntUserId); inDir.putExtra("timestamp",
		 * mStrTimeStamp); setResult(RESULT_OK, inDir); finish();
		 * startActivity(inDir); } });
		 */
	}

	private void loadSitesUsers() {
		QuerySitesUsers lp = new QuerySitesUsers();
		lp.execute();
		String strResult = "";
		try {
			strResult = lp.get();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
		if (strResult.equals("-1") == true) {
			Toast.makeText(Directory.this, "Can't not to connect to Server!",
					Toast.LENGTH_LONG).show();
		} else {
			if (strResult.equals("0") == true) {
				Toast.makeText(Directory.this, "Don't find out information!",
						Toast.LENGTH_LONG).show();
			} else {
				String[] strArrInfo = strResult.split("#@;");

				for (int i = 0; i < strArrInfo.length; i++) {
					ContentValues content = new ContentValues();
					content.put("site_url", strArrInfo[i].split("#@#")[0]);
					content.put("active", strArrInfo[i].split("#@#")[1]);
					content.put("buis_url", strArrInfo[i].split("#@#")[2]);
					mArrLstSitesUsers.add(content);
				}
			}
		}
		mIntImage = new int[mArrLstSitesUsers.size()];
		mStrBuisURL = new String[mArrLstSitesUsers.size()];
		ContentValues contentSitesUsers;
		String strSiteURL1 = null;
		String strSiteURL;
		for (int i = 0; i < mArrLstSitesUsers.size(); i++) {
			contentSitesUsers = mArrLstSitesUsers.get(i);
			mStrBuisURL[i] = contentSitesUsers.getAsString("buis_url");
			strSiteURL = contentSitesUsers.getAsString("site_url");
			int k = i + 1;
			if (k < mArrLstSitesUsers.size()) {
				contentSitesUsers = mArrLstSitesUsers.get(k);
				mStrBuisURL[k] = contentSitesUsers.getAsString("buis_url");
				strSiteURL1 = contentSitesUsers.getAsString("site_url");
				loadStoreRating(strSiteURL, i, strSiteURL1, ++i);
			} else {
				loadStoreRating(strSiteURL, i, null, 0);
			}

		}
	}

	private void loadStoreRating(String strSiteURL, int i, String strSiteURL1,
			int k) {
		DisplayMetrics metrics = this.getResources().getDisplayMetrics();
		int width = metrics.widthPixels;
		int height = metrics.heightPixels;
		LinearLayout layout = new LinearLayout(this);
		layout.setOrientation(LinearLayout.HORIZONTAL);
		layout.setPadding(0, 0, 0, 24);

		ImageView img = loadStoreImage(strSiteURL, i);
		LayoutParams layParams = new LayoutParams();
		layParams.width = width / 2;
		layParams.height = LayoutParams.WRAP_CONTENT;
		img.setLayoutParams(layParams);
		img.setPadding(0, 0, 24, 0);
		layout.addView(img);

		if ((strSiteURL1 != null) && (k != 0)) {
			ImageView img1 = loadStoreImage(strSiteURL1, k);
			LayoutParams layParams1 = new LayoutParams();
			layParams1.width = width / 2;
			layParams1.height = LayoutParams.WRAP_CONTENT;
			img1.setLayoutParams(layParams1);
			img1.setPadding(24, 0, 0, 0);
			layout.addView(img1);
		}
		mLiLayStore.addView(layout);
	}

	private ImageView loadStoreImage(String strSiteURL, int i) {
		ImageView img = null;
		QuerySites lpp = new QuerySites();
		lpp.execute(strSiteURL);
		String strResult = "";
		try {
			strResult = lpp.get();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
		if (strResult.equals("-1") == true) {
			Toast.makeText(Directory.this, "Can't not to connect to Server!",
					Toast.LENGTH_LONG).show();
		} else {
			if (strResult.equals("0") == true) {
				Toast.makeText(Directory.this, "Don't find out information!",
						Toast.LENGTH_LONG).show();
			} else {
				String[] strArrInfo = strResult.split("#@#");

				for (int j = 0; j < strArrInfo.length; j++) {
					mStrIcon = strArrInfo[2];
					/*
					 * mStrSiteName = strArrInfo[0]; mStrActive = strArrInfo[1];
					 * mStrSupport = strArrInfo[3];
					 */
				}
				img = new ImageView(Directory.this);
				loadStoreImage(img);
				img.setId(i);
				mIntImage[i] = img.getId();
			}
		}
		return img;
	}

	private void loadStoreImage(ImageView img) {
		new DownloadImageTask(img)
				.execute("http://reputation.bonothemes.com/admin/icons/" + mStrIcon);
		img.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(Directory.this, RatingPage.class);
				for (int i = 0; i < mIntImage.length; i++) {
					if (mIntImage[i] == v.getId()) {
						intent.putExtra("url", "http://" + mStrBuisURL[i]);
						Log.i("buis_url", mStrBuisURL[i]);
						break;
					}
				}
				intent.putExtra("username", mStrUsername);
				intent.putExtra("timestamp", mStrTimeStamp);
				intent.putExtra("logo", mStrLogo);
				intent.putExtra("coupon", mStrCoupon);
				intent.putExtra("id", mIntUserId);
				startActivity(intent);
				setResult(RESULT_OK, intent);
				finish();
			}
		});
	}

	private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
		ImageView bmImage;

		public DownloadImageTask(ImageView bmImage) {
			this.bmImage = bmImage;
		}

		protected Bitmap doInBackground(String... urls) {
			String urldisplay = urls[0];
			Bitmap mIcon11 = null;
			try {
				InputStream in = new java.net.URL(urldisplay).openStream();
				mIcon11 = BitmapFactory.decodeStream(in);
			} catch (Exception e) {
				Log.e("Error", e.getMessage());
				e.printStackTrace();
			}
			return mIcon11;
		}

		protected void onPostExecute(Bitmap result) {
			bmImage.setImageBitmap(result);
		}
	}

	private class QuerySitesUsers extends AsyncTask<String, String, String> {

		private String strResult;

		@Override
		protected String doInBackground(String... params) {
			strResult = mJDBC.selectSitesUsers(mStrUsername);
			Log.i("doInBG", strResult);
			return strResult;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
		}
	}

	private class QuerySites extends AsyncTask<String, String, String> {

		private String strResult;

		@Override
		protected String doInBackground(String... params) {
			Log.i("siteURL", params[0]);
			strResult = mJDBC.selectSites(params[0]);
			Log.i("doInBG", strResult);
			return strResult;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);

		}
	}

	@Override
	public void onBackPressed() {
		Intent intent = new Intent(this, Login.class);
		if ((mStrUsername != null) && (mStrTimeStamp != null)) {
			intent.putExtra("username", mStrUsername);
			intent.putExtra("timestamp", mStrTimeStamp);
			intent.putExtra("logo", mStrLogo);
			intent.putExtra("coupon", mStrCoupon);
			intent.putExtra("id", mIntUserId);
		}
		startActivity(intent);
		finish();
		super.onBackPressed();
	}
}
